package nl.vu.few.ibivu.biomodels.client;

import nl.vu.few.ibivu.biomodels.client.event.LoginStateChangedEvent;
import nl.vu.few.ibivu.biomodels.client.event.LoginStateChangedEventHandler;
import nl.vu.few.ibivu.biomodels.client.gin.BioModelsGinjector;
import nl.vu.few.ibivu.biomodels.shared.UserInfo;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class BioModels implements EntryPoint, LoginStateChangedEventHandler, AsyncCallback<UserInfo> {

	private static UserInfo userInfo;
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		GatewayServiceAsync gws = GWT.create(GatewayService.class);
		// FIXME
		// The initial authentication should be performed by a servlet
		// that serves dynamically the index page and insert the
		// login information necessary to initialize the GatewayPresenter
		// component for the first time.
		// See: http://code.google.com/webtoolkit/articles/dynamic_host_page.html
		//
		// In this case instead we perform a late check for the login status
		// using GWTRPC and we update the already built GatewayPresenter.
		//
		gws.getUserInfo(Window.Location.createUrlBuilder().setPath("/GatewayReturn.html").buildString(), this);
	}
	
	@Override
	public void onFailure(Throwable caught) {
		// TODO FIXME in case of error show some random text
	}
	
	@Override
	public void onSuccess(UserInfo result) {
		userInfo = result;
		BioModelsGinjector ginjector = GWT.create(BioModelsGinjector.class);
		LoginStateChangedEvent.register(ginjector.getEventBus(), this);
		Window.enableScrolling(false);
		Window.setMargin("0px");
		ginjector.getMainView().draw();
		// Goes to place represented on URL or default place
		ginjector.getPlaceHistoryHandler().handleCurrentHistory();
	}
	
	public static UserInfo getUserInfo() {
		return userInfo;
	}

	@Override
	public void onUserLogin(LoginStateChangedEvent event) {
		BioModels.userInfo = event.getUserInfo();
	}

	@Override
	public void onUserLogout(LoginStateChangedEvent event) {
		BioModels.userInfo = event.getUserInfo();
	}
}
